<template>
  <el-dialog :title="title" :visible.sync="showForm" @close="cancel" width="80%" append-to-body close-on-press-escape>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="总部编号" prop="zbbh">
            <el-input v-model="form.zbbh" placeholder="请输入总部编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="完工编号" prop="wgbh">
            <el-input
              v-model="form.wgbh"
              placeholder="请输入完工编号"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="khname">
            <el-input v-model="form.khname" placeholder="请选择客户名称">
              <el-button type="primary" slot="prepend" @click.native="selectUser"> 选择客户 </el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="税号" prop="sh">
            <el-input
              v-model="form.sh"
              placeholder="请输入税号"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户编号" prop="khname">
            <el-input v-model="form.bh" readonly placeholder="请输入客户名称" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户电话" prop="dh">
            <el-input v-model="form.dh" placeholder="请输入客户电话" clearable/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="银行卡号" prop="xhkh">
            <el-input
              v-model="form.xhkh"
              placeholder="请输入银行卡号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户地址" prop="dz">
            <el-input v-model="form.dz" placeholder="请输入客户地址" clearable/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否已开发票" prop="sfykfp">
            <el-select v-model="form.sfykfp" style="width: 100%;" placeholder="请选择">
              <el-option
                v-for="item in sfList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票票号" prop="fpph">
            <el-input
              v-model="form.fpph"
              placeholder="发票票号"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="开票金额(元)" prop="kpje">
            <el-input
              v-model="form.kpje"
              placeholder="开票金额"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="是否回款" prop="sfhk">
            <el-select v-model="form.sfhk" style="width: 100%;" placeholder="请选择">
              <el-option
                v-for="item in hkList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="回款金额" prop="hkje">
            <el-input v-model="form.hkje" placeholder="请输入回款金额" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="回款日期" prop="hksj">
            <el-date-picker clearable
                            style="width: 100%"
                            v-model="form.hksj"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择回款时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="完工日期" prop="wgrq">
            <el-date-picker clearable
                            style="width: 100%"
                            v-model="form.wgrq"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择完工时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到账账号" prop="dzzh">
            <el-select v-model="form.dzzh" style="width: 100%;" placeholder="请选择">
              <el-option
                v-for="item in dzzhList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="附件" prop="fj">
            <el-upload
              class="upload-demo"
              :action="src"
              :on-success="handleSuccess"
              :on-error="handleError"
              :before-remove="handleRemove"
              :headers="uploadHeaders"
              multiple
              accept=".xlsx, .xls"
              :limit="1"
              :file-list="fjList"
              :on-exceed="handleExceed"
              :on-preview="handlePreview"
            >
              <el-button size="small" type="primary"> <i class="el-icon-upload"></i> 点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传Excel文件</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="bz">
            <el-input
              maxlength="1000"
              :autosize="{ minRows: 3, maxRows: 4 }"
              show-word-limit
              v-model="form.bz"
              type="textarea"
              placeholder="请输入内容" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
<!--    <BhList v-if="showYwd" :showBh="showYwd" @closeDialog="closeDialog" @selectData="selectData"></BhList>-->
    <khList v-if="showUser" :showUser="showUser" @selectData="selectData" @closeDialog="closeDialog"></khList>
    <PdfPreView
      v-if="showPdf"
      :showPdf="showPdf"
      :fjId="fjId"
      :title="fjTitle"
      @cancel="cancelPdf"
    ></PdfPreView>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="ShowBtn" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import PdfPreView from '@/views/components/componse/PdfView.vue'
// import BhList from '@/views/gd/wgd/BhList.vue'
import khList from "@/views/gd/ywd/khList.vue";
import { getToken } from '@/utils/auth'
import { addWgd, getWgd, updateWgd } from '@/api/gd/wgd'
import { delFj, getFj, getFjById } from '@/api/gd/fj'
export default {
  name: 'formInfo',
  components: { PdfPreView, khList },
  props: {
    title: {
      type: String
    },
    formInfo: {
      type: Object
    },
    ShowBtn: {
      type: Boolean
    },
    showForm: {
      type: Boolean
    }
  },
  data() {
    return {
      showUser: false,
      form: {},
      sfList: [],
      hkList: [],
      dzzhList: [],
      src: this.uploadSrc + '/gd/fj/file/upload',
      fjId: "",
      fjTitle: "",
      showPdf: false,
      showYwd: false,
      fjList: [],
      uploadHeaders: { 'Authorization': 'Bearer ' + getToken() }, // 如果需要CSRF保护的话
      // 按钮loading
      buttonLoading: false,
      rules: {
        id: [
          { required: true, message: "id不能为空", trigger: "blur" }
        ],
        zbbh: [
          { required: true, message: "总部编号不能为空", trigger: "change" }
        ],
        sfykfp: [
          { required: true, message: "是否已开发票不能为空", trigger: "blur" }
        ],
        bh: [
          { required: true, message: "请选择客户编号", trigger: "blur" }
        ],
      },
    }
  },
  created() {
    this.form = this.formInfo
    this.init()
  },
  methods: {
    closeDialog() {
      this.showUser = false
    },
    selectData(row) {
      this.$set(this.form, 'khname', row.khname)
      this.$set(this.form, 'dh', row.dh)
      this.$set(this.form, 'dz', row.dz)
      this.$set(this.form, 'xhkh', row.xhkh)
      this.$set(this.form, 'sh', row.sh)
      this.$set(this.form, 'bh', row.bh)
      this.closeDialog()
    },
    selectUser() {
      this.showUser = true
    },
    init() {
      this.getDict()
      this.initFj()
    },
    initFj() {
      let than = this
      if (this.form.fj !== "" && this.form.fj !== null && this.form.fj !== undefined) {
        getFj(this.form.fj).then(res => {
          if (res !== null && res.data !== null) {
            const obj = {
              fjid: res.data.fjid,
              name: res.data.fjname,
              path: res.data.fjpath
            }
            than.fjList.push(obj)
          }
        })
      }
      if (this.form.fjpdf !== "" && this.form.fjpdf !== null && this.form.fjpdf !== undefined) {
        getFj(this.form.fjpdf).then(res => {
          if (res !== null && res.data !== null) {
            const obj = {
              fjid: res.data.fjid,
              name: res.data.fjname,
              path: res.data.fjpath
            }
            than.fjList.push(obj)
          }
        })
      }
    },
    getDict() {
      this.getDicts("sys_yes_no").then(res => {
        this.sfList = res.data
      })
      // 是否回款
      this.getDicts("gd_sfhk").then(res => {
        this.hkList = res.data
      })
      // 到账账号
      this.getDicts("gd_dzzh").then(res => {
        this.dzzhList = res.data
      })
    },
    cancel() {
      this.$emit("close")
    },
    // ======  上传开始  ======
    handleSuccess(response, file) {
      if(this.ShowBtn) {
        // 更新状态或者通知用户上传成功
        this.$message.success('上传成功');
        // 上传成功以后，将id设置
        this.form.fj = response.fj
        this.form.fjpdf = response.fjpdf
        if (this.form.id !== undefined) {
          updateWgd(this.form).then(objs => {
            getWgd(this.form.id).then(async response => {
              this.fjList = []
              let obj = response.data
              if (obj.fjpdf !== "" && obj.fjpdf !== null && obj.fjpdf !== undefined) {
                await getFj(obj.fjpdf).then(res => {
                  if (res !== null && res.data !== null) {
                    const data = {
                      fjid: res.data.fjid,
                      name: res.data.fjname,
                      path: res.data.fjpath
                    }
                    this.fjList.push(data)
                  }
                })
              }
              if (obj.fj !== "" && obj.fj !== null && obj.fj !== undefined) {
                await getFj(obj.fj).then(res => {
                  if (res !== null && res.data !== null) {
                    const data = {
                      fjid: res.data.fjid,
                      name: res.data.fjname,
                      path: res.data.fjpath
                    }
                    this.fjList.push(data)
                  }
                })
              }
            })
          })
        }
      }
    },
    // 上传失败回调
    handleError(err, file) {
      // 处理错误并通知用户
      this.$message.error('上传失败：', err);
      this.fjList = []
    },
    // 删除回调
    handleRemove(file, fileList) {
      // 调用删除附件功能，将附件进行删除
      if (this.ShowBtn) {
        this.$modal.confirm('请确认是否删除附件名称为：'+file.name+' 的数据?').then(() => {
          let fjId = []
          fjId.push(file.fjid)
          let ids = []
          fileList.forEach(item => {
            ids.push(item.fjid)
          })
          ids.push(file.fjid)
          delFj(fjId).then(res => {
            if (res.code === 200) {
              this.$message.success("删除成功！")
              // 删除后更新数据
              if (ids !== '' && ids !== null) {
                this.form.fj = ""
                this.form.fjpdf = ""
                updateWgd(this.form).then(objs => {
                  getWgd(this.form.id).then(async response => {
                    this.fjList = []
                    let obj = response.data
                    if (obj.fjpdf !== "" && obj.fjpdf !== null && obj.fjpdf !== undefined) {
                      await getFj(obj.fjpdf).then(res => {
                        if (res !== null && res.data !== null) {
                          const data = {
                            fjid: res.data.fjid,
                            name: res.data.fjname,
                            path: res.data.fjpath
                          }
                          this.fjList.push(data)
                        }
                      })
                    }
                    if (obj.fj !== "" && obj.fj !== null && obj.fj !== undefined) {
                      await getFj(obj.fj).then(res => {
                        if (res !== null && res.data !== null) {
                          const data = {
                            fjid: res.data.fjid,
                            name: res.data.fjname,
                            path: res.data.fjpath
                          }
                          this.fjList.push(data)
                        }
                      })
                    }
                  })
                })
              }
            }
          })
        }).catch(() => {
          fileList.push(file)
        })
      }else {
        this.fjList = fileList
        this.$message.error("当前是预览状态，禁止删除")
      }

    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件`);
    },
    // 文件点击回调
    handlePreview(file) {
      let id = file.fjid || file.response.fj
      let suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (suffix === 'pdf') {
        this.showPdf = true
        this.fjId = id
        this.fjTitle = "PDF预览"
      }else if (suffix === 'xlsx' || suffix === 'xls') {
        getFjById(id, 'blob').then(response => {
          const binaryData = [];
          binaryData.push(response);
          let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
          const link = document.createElement('a');
          link.href = url
          link.download = file.name;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
      }

    },
    cancelPdf() {
      this.showPdf = false
    },
    // ======  上传结束  ====
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.status = '0'
          if (this.form.id != null) {
            updateWgd(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel()
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addWgd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel()
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
  }
}
</script>

<style scoped>

</style>
